package com.yuexun.dhdoctor.module.login.ui;

import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.config.ScreenUtil;
import com.yuexun.dhdoctor.module.login.bean.AreaBean;
import com.yuexun.dhdoctor.module.login.bean.AreaHospBean;
import com.yuexun.dhdoctor.module.login.bean.LoginBean;
import com.yuexun.dhdoctor.module.login.bean.UserBean;
import com.yuexun.dhdoctor.module.login.model.impl.AreaHospModel;
import com.yuexun.dhdoctor.module.login.model.impl.LoginModel;
import com.yuexun.dhdoctor.module.login.model.impl.MenuPhoneModel;
import com.yuexun.dhdoctor.module.login.presenter.IMenuPhonePresenter;
import com.yuexun.dhdoctor.module.login.presenter.impl.AreaHospPresenter;
import com.yuexun.dhdoctor.module.login.presenter.impl.LoginPresneter;
import com.yuexun.dhdoctor.module.login.presenter.impl.MenuPhonePresenter;
import com.yuexun.dhdoctor.module.login.presenter.impl.VerifyPresenter;
import com.yuexun.dhdoctor.module.login.ui.view.IAreaHospView;
import com.yuexun.dhdoctor.module.login.ui.view.ILoginView;
import com.yuexun.dhdoctor.module.login.ui.view.IMenuPhoneView;
import com.yuexun.dhdoctor.module.login.ui.view.IVerifyView;
import com.yuexun.dhdoctor.module.main.ui.Act_Main;
import com.yuexun.dhdoctor.module.my.ui.Act_Change_Psw;
import com.yuexun.dhdoctor.util.PermissionUtils;
import com.yuexun.dhdoctor.widget.LoadingDialog;
import com.yuexun.library.AbstractWheel;
import com.yuexun.library.OnWheelChangedListener;
import com.yuexun.library.adapters.ArrayWheelAdapter;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/6/30.
 */
public class Act_Login extends KJActivity implements ILoginView, ActivityCompat.OnRequestPermissionsResultCallback, IMenuPhoneView, IAreaHospView, IVerifyView {

    @Bind(R.id.login_name_edt)
    EditText loginNameEdt;
    @Bind(R.id.login_password_edt)
    EditText loginPasswordEdt;
    @Bind(R.id.login_zone)
    TextView login_zone;
    @Bind(R.id.login_hospital)
    TextView login_hospital;
    @Bind(R.id.login_btn)
    Button loginBtn;
    @Bind(R.id.et_code)
    EditText etCode;
    @Bind(R.id.btn_get_code)
    Button btnGetCode;

    private LoginPresneter presenter;
    IMenuPhonePresenter phonePresenter;
    AreaHospPresenter areaHospPresenter;

    LoadingDialog dialog;
    String device_token;
    PushAgent mPushAgent;

    List<AreaBean> areaBeans = new ArrayList<>();
    String[] zones = new String[]{};
    List<AreaHospBean> areaHospitals = new ArrayList<>();
    String hospitals[] = new String[]{};
    int zoneId = 0, hospitalId = 0;
    int zonePosition = 0;
    int hospitalPosition = 0;
    VerifyPresenter presenter_verify;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_login);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        presenter_verify = new VerifyPresenter(new LoginModel(), this);
        if (Build.VERSION.SDK_INT >= 23) {
            PermissionUtils.requestMultiPermissions(this, mPermissionGrant);
        }
        dialog = new LoadingDialog(aty);
        presenter = new LoginPresneter(new LoginModel(), this);
        phonePresenter = new MenuPhonePresenter(new MenuPhoneModel(), this);
        areaHospPresenter = new AreaHospPresenter(new AreaHospModel(), this);
        Map<String, String> params = new HashMap<>();
        areaHospPresenter.inquireAreaWithHospList(params);
//        loginNameEdt.setText("666");
//        loginPasswordEdt.setText("123456@Abc");

        loginNameEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (loginNameEdt.getText().toString().length() > 0 && loginPasswordEdt.getText().toString().length() > 0) {
                    loginBtn.setBackgroundResource(R.drawable.login_button_bg);
                    loginBtn.setEnabled(true);
                } else {
                    loginBtn.setBackgroundResource(R.drawable.login_unbutton_bg);
                    loginBtn.setEnabled(false);
                }
            }
        });
        loginPasswordEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (loginNameEdt.getText().toString().length() > 0 && loginPasswordEdt.getText().toString().length() > 0) {
                    loginBtn.setBackgroundResource(R.drawable.login_button_bg);
                    loginBtn.setEnabled(true);
                } else {
                    loginBtn.setBackgroundResource(R.drawable.login_unbutton_bg);
                    loginBtn.setEnabled(false);
                }
            }
        });

        //友盟
        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.enable();
        PushAgent.getInstance(this).onAppStart();
        device_token = UmengRegistrar.getRegistrationId(this);
        Log.e("jx", device_token);

        login_zone.setText(PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.AREANAME));
        login_hospital.setText(PreferenceHelper.readString(this, AppConfig.USER_INFO, AppConfig.HOSPITALNAME));
    }

    @Override
    @OnClick({R.id.login_btn, R.id.login_zone_ll, R.id.login_hospital_ll,R.id.btn_get_code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                String code = etCode.getText().toString().trim();
//                if(TextUtils.isEmpty(code)) {
//                    ViewInject.toast("请输入验证码");
//                    return;
//                }
                final String user_Id = loginNameEdt.getText().toString().trim();
                if(TextUtils.isEmpty(user_Id)) {
                    ViewInject.toast("请输入工号");
                    return;
                }

                final String password = loginPasswordEdt.getText().toString().trim();
                if(TextUtils.isEmpty(password)) {
                    ViewInject.toast("请输入密码");
                    return;
                }
                if(login_zone.getText().length()>0&&login_hospital.getText().length()>0) {
                    Map<String, String> params = new HashMap<>();
                    params.put("username", user_Id);
                    params.put("password", password);
                    params.put("deviceToken", device_token);
                    params.put("hospId", hospitalId + "");
                    params.put("appKey", "Android");
                    params.put("code", code);
                    presenter.dologin(params);
                }
                else {
                    ViewInject.toast("请先选择所在地区和所在医院");
                }
                break;
            case R.id.login_zone_ll:
                if(zones!=null && zones.length>0){
                    zoneDialog();
                }
                break;
            case R.id.login_hospital_ll:
                if(hospitals!= null && hospitals.length>0){
                    hospitalDialog();
                }
                break;
            case R.id.btn_get_code:
                String userId = loginNameEdt.getText().toString().trim();
                if(TextUtils.isEmpty(userId)) {
                    ViewInject.toast("请输入工号");
                    return;
                }
                btnGetCode.setEnabled(false);
                countTask.start();
                String szImei = Settings.System.getString(aty.getContentResolver(), Settings.System.ANDROID_ID);
                Map<String, String> params_verify = new HashMap<>();
                params_verify.put("setNo",szImei);
                params_verify.put("hospId",hospitalId + "");
                params_verify.put("jobNum",userId);
                presenter_verify.sendVerify(params_verify);
                break;
            default:
                break;
        }
    }

    private CountDownTimer countTask = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            btnGetCode.setText(millisUntilFinished / 1000 + "S重新发送");
        }

        @Override
        public void onFinish() {
            btnGetCode.setText("发送短信验证码");
            btnGetCode.setEnabled(true);
        }
    };

    @Override
    public void loadingDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                break;

            case AppConfig.DISMISS_DIALOG:
                dialog.dismiss();
                break;
            default:
                break;
        }
    }

    @Override
    public void doInLogin(LoginBean loginBean) {
        if (loginBean.getStatus() == 200) {
            String filename = AppConfig.USER_INFO;
            PreferenceHelper.write(aty, filename, AppConfig.JOB_ID, loginBean.getDatas().get(0).getJobNum());
            PreferenceHelper.write(aty, filename, AppConfig.SESSION_ID, loginBean.getDatas().get(0).getSessionUuid());
            PreferenceHelper.write(aty, filename, AppConfig.ROLETYPE, loginBean.getDatas().get(0).getRoleType());
            PreferenceHelper.write(aty, filename, AppConfig.DEPARTMENTID, loginBean.getDatas().get(0).getDepartmentId());
            PreferenceHelper.write(aty, filename, AppConfig.DEPARTMENTNAME, loginBean.getDatas().get(0).getDepartmentName());
            PreferenceHelper.write(aty, filename, AppConfig.ACCOUNT_ID, loginBean.getDatas().get(0).getAccountId());

            PreferenceHelper.write(aty, filename, AppConfig.USER_ID, loginBean.getDatas().get(0).getAccountId());
            PreferenceHelper.write(aty, filename, AppConfig.USER_NAME, loginBean.getDatas().get(0).getFullName());
            PreferenceHelper.write(aty, filename, AppConfig.USER_DEPT, loginBean.getDatas().get(0).getDepartmentName());

            PreferenceHelper.write(aty, filename, AppConfig.HOSPKEY, loginBean.getDatas().get(0).getAreaHospitalEntity().getSlHospKey());

            PreferenceHelper.write(aty, filename, AppConfig.RALATEHISACCOUNTId, loginBean.getDatas().get(0).getRelatedHISAccountId());
            PreferenceHelper.write(aty, filename, AppConfig.SIHOSPCODE, loginBean.getDatas().get(0).getAreaHospitalEntity().getSlHospCode());

            // 自动账号登入
            PreferenceHelper.write(aty, filename, AppConfig.ISLOGIN, false);
            PreferenceHelper.write(aty, filename, AppConfig.USERNAME, loginNameEdt.getText().toString());
            PreferenceHelper.write(aty, filename, AppConfig.USERPWD, loginPasswordEdt.getText().toString());
            PreferenceHelper.write(aty, filename, AppConfig.USERDEVICE, device_token);
            PreferenceHelper.write(aty, filename, AppConfig.USERAPPKEY, "Android");
            PreferenceHelper.write(aty, filename, AppConfig.AREAID, zoneId);
            PreferenceHelper.write(aty, filename, AppConfig.HOSPITALID, hospitalId);
            PreferenceHelper.write(aty, filename, AppConfig.AREANAME, login_zone.getText().toString());
            PreferenceHelper.write(aty, filename, AppConfig.HOSPITALNAME, login_hospital.getText().toString());

            if(loginBean.getDatas().get(0).getEditPwd().equals("0"))
            {
                Intent intent_share = new Intent(aty, Act_Change_Psw.class);
                startActivity(intent_share);
            }
            else {
                mPushAgent.setAlias(loginBean.getDatas().get(0).getAccountId() + "", "ACCOUNT_ID");
                Map<String, String> params = new HashMap<>();
                params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
                phonePresenter.getMenuPhone(params);
            }
        } else {
            ViewInject.toast(loginBean.getMessage());
        }
    }

    @Override
    public void getUserInfo(UserBean userBean) {

    }

    @Override
    public void getAreaWithHospList(BaseEntity<AreaBean> baseEntity) {
        if(baseEntity.getStatus().equals("200")){
            areaBeans = baseEntity.getDatas();
            AppConfig.AREA_BEAN = areaBeans;
            List<String> list=new ArrayList<String>();
            for(AreaBean areaBean : areaBeans){
                list.add(areaBean.getAreaName());
            }
            zones = list.toArray(new String[list.size()]);
            zonePosition = 0;
            initHosp();
        }
    }

    private void initHosp(){
        login_zone.setText(zones[zonePosition]);
        zoneId = areaBeans.get(zonePosition).getId();
        areaHospitals = areaBeans.get(zonePosition).getHospList();
        List<String> list=new ArrayList<String>();
        for(AreaHospBean hospBean : areaHospitals){
            list.add(hospBean.getHospitalName());
        }
        hospitals = list.toArray(new String[list.size()]);
        if(PreferenceHelper.readInt(aty, AppConfig.USER_INFO, AppConfig.HOSPITALID) == 0){
            login_hospital.setText(hospitals[0]);
            hospitalId = areaHospitals.get(0).getId();
        }else{
            login_hospital.setText(PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.HOSPITALNAME));
            hospitalId = PreferenceHelper.readInt(aty, AppConfig.USER_INFO, AppConfig.HOSPITALID);
        }
    }

    private void zoneDialog() {
        final Dialog dialog = new Dialog(this, R.style.dialog4style);
        View view = LayoutInflater.from(this).inflate(R.layout.picker_content, null);
        view.findViewById(R.id.picker_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.picker_done).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHosp();
                dialog.dismiss();
            }
        });

        final AbstractWheel zone = (AbstractWheel) view.findViewById(R.id.wheel);
        zone.setVisibleItems(3);
//        zone.setCyclic(true);
        ArrayWheelAdapter<String> adapter =
                new ArrayWheelAdapter<String>(this, zones);
        adapter.setTextSize(18);
        zone.setViewAdapter(adapter);
        zone.setCurrentItem(zonePosition);
        zone.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(AbstractWheel wheel, int oldValue, int newValue) {
                zonePosition = newValue;
            }
        });

        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = ScreenUtil.getScreenWidth(this);
        params.gravity = Gravity.BOTTOM;
        dialog.getWindow().setAttributes(params);
        dialog.getWindow().setWindowAnimations(R.style.dialog_anim_style);
        dialog.show();
    }

    private void hospitalDialog() {
        final Dialog dialog = new Dialog(this, R.style.dialog4style);
        View view = LayoutInflater.from(this).inflate(R.layout.picker_content, null);
        view.findViewById(R.id.picker_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.picker_done).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login_hospital.setText(hospitals[hospitalPosition]);
                hospitalId = areaHospitals.get(hospitalPosition).getId();
                dialog.dismiss();
            }
        });

        final AbstractWheel hospital = (AbstractWheel) view.findViewById(R.id.wheel);
        hospital.setVisibleItems(3);
//        hospital.setCyclic(true);
        ArrayWheelAdapter<String> adapter =
                new ArrayWheelAdapter<String>(this, hospitals);
        adapter.setTextSize(18);
        hospital.setViewAdapter(adapter);
        hospital.setCurrentItem(hospitalPosition);
        hospital.addChangingListener(new OnWheelChangedListener() {
            @Override
            public void onChanged(AbstractWheel wheel, int oldValue, int newValue) {
                hospitalPosition = newValue;
            }
        });

        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = ScreenUtil.getScreenWidth(this);
        params.gravity = Gravity.BOTTOM;
        dialog.getWindow().setAttributes(params);
        dialog.getWindow().setWindowAnimations(R.style.dialog_anim_style);
        dialog.show();
    }

    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PermissionUtils.CODE_RECORD_AUDIO:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_RECORD_AUDIO", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_GET_ACCOUNTS:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_GET_ACCOUNTS", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_READ_PHONE_STATE:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_READ_PHONE_STATE", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_CALL_PHONE:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_CALL_PHONE", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_CAMERA:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_CAMERA", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_ACCESS_FINE_LOCATION:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_ACCESS_FINE_LOCATION", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_ACCESS_COARSE_LOCATION:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_ACCESS_COARSE_LOCATION", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_READ_EXTERNAL_STORAGE:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_READ_EXTERNAL_STORAGE", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE:
                    Toast.makeText(Act_Login.this, "Result Permission Grant CODE_WRITE_EXTERNAL_STORAGE", Toast.LENGTH_SHORT).show();
                    break;
                case PermissionUtils.CODE_MULTI_PERMISSION:
                    Toast.makeText(Act_Login.this, "Result All Permission Grant", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void getMenuPhone(String s) {
        dialog.dismiss();
        if (s.contains("全院日报")) {
            AppConfig.QYRB = true;
        }

        if (s.contains("报表查询")) {
            AppConfig.BBCX = true;
        }

        showActivity(aty, Act_Main.class);
        finish();
    }

    @Override
    public void sendVerify(BaseEntity<String> s) {
        if(s.getStatus().equals("200")){
            try {
                JSONObject jsonObject = JSONObject.parseObject(s.getDatas().get(0));
                int code = jsonObject.getInteger("code");
                String description = jsonObject.getString("desc");
                ViewInject.toast(description);
            } catch(Exception e) {
                ViewInject.toast("发送验证码失败,请稍后再试");
            }
        }
        else{
            ViewInject.toast(s.getMessage());
        }
    }
}
